/**
 * 
 */
package com.wr.interceptor;

import com.google.common.base.Joiner;
import com.wr.cmmon.CommonConstants;
import com.wr.cmmon.UserContext;
import com.wr.config.FtpConfig;
import com.wr.model.RestResponse;
import com.wr.model.User;
import com.wr.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

  
  @Autowired
  private UserService userService;
  @Autowired
  private FtpConfig ftpConfig;

  
  @Override
  public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler)
          throws Exception {
    Map<String, String[]> map = req.getParameterMap();
    map.forEach((k,v) ->req.setAttribute(k, Joiner.on(",").join(v)));
    String requestURI = req.getRequestURI();
    if (requestURI.startsWith("/static") || requestURI.startsWith("/error")) {
      return true;
    }
    Cookie cookie = WebUtils.getCookie(req, CommonConstants.TOKEN_COOKIE);
    if (cookie != null && StringUtils.isNoneBlank(cookie.getValue())) {
        RestResponse<User> rest = userService.getUserByToken(cookie.getValue());
        User user = rest.getResult();
        if (user != null) {
          req.setAttribute(CommonConstants.LOGIN_USER_ATTRIBUTE, user);
          UserContext.setUser(user);
        }
    }
    req.setAttribute("IMAGE_BASE_URL",ftpConfig.getIMAGE_BASE_URL());

    return true;
  }
  

  @Override
  public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler,
                         ModelAndView modelAndView) {

  }
  
  

  @Override
  public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex)
          throws Exception {
    UserContext.remove();
  }
}
